package com.gjy.spring.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-02-17 16:16:09
 */
@Aspect
@Component
public class TimeoutAspect {

    @Resource
    private ThreadPoolTaskExecutor fileAsync;

    @Around("@annotation(timeout)")
    public Object handleTimeout(ProceedingJoinPoint joinPoint, Timeout timeout) {
        Future<Object> future = fileAsync.submit(() -> {
            try {
                return joinPoint.proceed();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        });

        try {
            return future.get(timeout.timeout(), TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            future.cancel(true);
            return "接口执行超时";
        } catch (Exception e) {
            return "内部错误";
        }
    }

}
